package com.ltmonitor.web.controller.mobile;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.Department;
import com.ltmonitor.entity.GPSRealData;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.service.IDepartmentService;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.MapFixService;
import com.ltmonitor.util.Constants;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.vo.PointLatLng;
import com.ltmonitor.web.controller.GenericAction;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.vo.GpsData;

/**
 * 实时数据查询
 * 
 * @author DELL
 * 
 */
public class MobileRealDataAction extends GenericAction {
	private static String REGISTER_KEY = "registerVehicleIds";
	/**
	 * session 主键，存放此主键的map
	 */
	private static String UPDATE_KEY = "session_update_realdata";
	

	@Autowired
	private IRealDataService realDataService;
	

	/**
	 * 刷新实时数据，前端不断的采用定时刷新的方式获取实时数据，刷新实时数据表格。 如果和以前的数据没有变化，则直接不刷新，只刷新GPS数据发生变化的数据
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/realData.action")
	public JsonMessage refreshRealData(long vehicleId) {
		if (vehicleId > 0) {
			// 单车监控，用于生成监控车辆轨迹
			try {
				VehicleData vd = this.vehicleDataService.load(vehicleId);

				GpsData gd = new GpsData();
				if (realDataService != null) {
					GPSRealData rd = realDataService.get(vd.getSimNo());
					if (rd != null) {
						// 将实时数据更新到map
						// updateMap(resultMap, rd);
						gd.setPlateNo(rd.getPlateNo());
						String alarmState = rd.getAlarmState();
						//int alarm = Integer.valueOf(alarmState, 2);
						String alarmDescr = this.getAlarmDescr(alarmState);
						gd.setAlarm(alarmDescr);
						String strStatus = rd.getStatus();
						//int status = Integer.valueOf(strStatus, 2);
						strStatus = this.getStatusDescr(strStatus);
						gd.setStatus(strStatus);
						String strSignal = this.getSignalDescr(rd.getSignalState());
						gd.setSignal(strSignal);
						// 坐标加偏
						PointLatLng pl = MapFixService.fix(rd.getLatitude(), rd.getLongitude(),
								Constants.MAP_GOOGLE);
						gd.setLat(pl.getLat());
						gd.setLng(pl.getLng());
						gd.setSendTime(DateUtil.datetimeToString(rd.getSendTime()));
						gd.setSpeed(rd.getVelocity());
						gd.setDirection(rd.getDirection());
						gd.setLocation(rd.getLocation());
						gd.setSimNo(rd.getSimNo());
						gd.setOnline(rd.getOnline());
						return json(true, gd);
					} else 
						return json(false, "没有查询到该车辆的实时数据");
				}else
					return json(false, "无法连接到GPS服务器");
				// this.convert(resultMap, true);
				// } else
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex); 
				return json(false, ex.getMessage());
			}
		} else {

			return json(false, "车辆ID不能为0");
		}

	}



	/**
	 * 0：无特定位置； 1：圆形区域； 2：矩形区域； 3：多边形区域； 4：路段
	 * 
	 * @param areaType
	 * @return
	 */
	protected String getAreaTypeDescr(int areaType) {
		if (areaType == 0)
			return "无特定位置";
		else if (areaType == 1)
			return "圆形区域";
		else if (areaType == 2)
			return "矩形区域";
		else if (areaType == 3)
			return "多边形区域";
		else if (areaType == 4)
			return "路段";
		return "未知区域类型";
	}

	protected String getDirectionDescr(int direction) {
		Map directionMap = new HashMap();
		String descr = "";
		if (direction == 0) {
			descr = "正东";
		} else if (direction == 90) {
			descr = "正北";
		} else if (direction == 180) {
			descr = "正西";
		} else if (direction == 270) {
			descr = "正南";
		} else if (direction == 45) {
			descr = "东北";
		} else if (direction == 135) {
			descr = "西北";
		} else if (direction == 225) {
			descr = "西南";
		} else if (direction == 315) {
			descr = "东南";
		} else if (direction < 90) {
			descr = "东偏北" + direction + "度";
		} else if (direction > 90 && direction < 180) {
			descr = "西偏北" + (180 - direction) + "度";
		} else if (direction > 180 && direction < 270) {
			descr = "西偏南" + (direction - 180) + "度";
		} else if (direction > 270 && direction < 360) {
			descr = "东偏南" + (360 - direction) + "度";
		}
		return descr;
	}

	protected String getStatusDescr(String status) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isNullOrEmpty(status) == false) {
			char[] ch = status.toCharArray();
			if (ch.length == 32) {
				int m = 31;
				int c = ch[m - 0] - 48;
				sb.append(c == 1 ? "ACC开" : "ACC关").append(",");
				c = ch[m - 1] - 48;
				sb.append(c == 1 ? "定位" : "未定位").append(",");
				c = ch[m - 4] - 48;
				sb.append(c == 1 ? "停运" : "运营").append(",");
				c = ch[m - 10] - 48;
				sb.append(c == 1 ? "油路断开" : "油路正常").append(",");
				c = ch[m - 11] - 48;
				sb.append(c == 1 ? "电路断开" : "电路正常").append(",");
				c = ch[m - 12] - 48;
				sb.append(c == 1 ? "车门加锁" : "车门解锁").append(",");
			}
		}

		return sb.toString();
	}

	private static String[] signalDescr = new String[] { "近光灯", "远光灯", "右转向灯",
			"左转向灯", "制动", "倒档" };

	protected String getSignalDescr(int signal) {
		StringBuilder sb = new StringBuilder();
		String strStatus = Integer.toBinaryString(signal);
		strStatus = StringUtil.leftPad(strStatus, 32, '0');

		char[] ch = strStatus.toCharArray();
		for (int m = 0; m < ch.length && m < signalDescr.length; m++) {
			int c = ch[31 - m] - 48;
			if (StringUtil.isNullOrEmpty(signalDescr[m]) == false) {
				sb.append(signalDescr[m]).append(c == 1 ? "开" : "关")
						.append(",");
			}
		}

		return sb.toString();
	}

	/**
	 * 报警描述
	 * 
	 * @param alarm
	 * @return
	 */
	protected String getAlarmDescr(String alarm) {
		StringBuilder sb = new StringBuilder();

		if (StringUtil.isNullOrEmpty(alarm) == false) {
			char[] ch = alarm.toCharArray();
			for (int m = 0; m < ch.length; m++) {
				int tag = Integer.parseInt("" + ch[m]);
				if (tag == 1) {
					int alarmId = 31 - m; // 倒序，转换为部标的报警序号
					BasicData bd = basicDataService.getBasicDataByCode(""
							+ alarmId, "AlarmType");
					if (bd != null) {
						sb.append(bd.getName()).append(",");
					}
				}
			}
		}

		return sb.toString();
	}
	
	


}
